<template>
  <div class="settings-base">
    <el-form ref="infoFormRef"
             :model="userForm"
             :rules="rules"
             class="base-form"
             label-position="top"
             label-width="120px">
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="userForm.nickname" placeholder="请输入昵称"/>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" placeholder="请输入邮箱"/>
      </el-form-item>

      <el-form-item class="btn-group">
        <el-button type="primary" @click="submitForm(infoFormRef)">
          更新基本信息
        </el-button>
      </el-form-item>
    </el-form>

    <div class="upload-warp">
      <el-avatar :size="100" :src="imageUrl" class="info-avatar"/>
      <UploadButton v-model="imageUrl" button-text="更换头像" style="margin-top: 10px"/>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { ElLoading, ElNotification, type FormInstance, } from 'element-plus';
import { UploadButton } from '@/components/upload';
import { sysUserBaseModify } from '@/api/api-sys.ts';
import { useUserStore } from '@/store';

const userStore = useUserStore();
const imageUrl = ref(userStore.avatar);
const infoFormRef = ref<FormInstance>();
const userForm = reactive({
  nickname: userStore.nickname,
  email: userStore.email,
});
const rules = reactive({
  nickname: [{required: true, message: '请输入昵称', trigger: 'blur'}],
  //email: [{required: true, message: '请输入邮箱', trigger: 'blur'}],
});

// =========================== 表单 =======================
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (!valid) {
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    let params = {
      nickname: userForm.nickname,
      email: userForm.email,
      avatar: imageUrl.value
    };
    // 提交数据
    sysUserBaseModify(params).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      userStore.loadInfo();
    }).finally(() => loading.close())
  });
};
</script>

<style lang="scss" scoped>
@use "@/styles/var" as _v;

.settings-base {
  display: flex;

  .base-form {
    width: 60%;

    :deep(.el-form-item) {
      margin-bottom: 22px;

      .el-form-item__content {
        .el-input,
        .el-cascader {
          width: 100%;
        }
      }
    }

    .btn-group {
      :deep(.el-form-item__content) {
        justify-content: center;
      }
    }
  }

  .upload-warp {
    padding-left: 24px;
    width: 40%;
    margin-bottom: 24px;
    text-align: center;
  }

  @media screen and (max-width: _v.$lg) {
    flex-direction: column-reverse;
    .base-form {
      width: 100%;
    }
    .upload-warp {
      padding-left: 0;
      width: 100%;
    }
  }
}
</style>
